package com.fire.user.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fire.core.base.controller.BaseController;
import com.fire.core.service.ITMitErrorCodeService;
import com.fire.core.service.ITMitServiceDicBaseServices;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.BlogUtil;
import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.model.TMitChannel;
import com.fire.user.request.ContextReq;
import com.fire.user.request.WchatPushxReq;
import com.fire.user.request.WchatShareReq;
import com.fire.user.service.ITMitChannelService;
import com.fire.user.service.IUserService;
import com.fire.user.service.IUserWxService;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;

@Controller
public class WxController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(WxController.class);

	@Autowired
	IUserWxService serWxService;
	@Autowired
	ITMitServiceDicBaseServices baseService;
	@Autowired
	ITMitErrorCodeService itMitErrorCodeService;
	@Autowired
	ITMitChannelService iTMitChannelService;
	@Autowired
	IUserService userService;
	@Value("${weChat.scope}")
	private String scope;


	private static String WXCALLBACKURL = "WXCALLBACKURL";

	/**
	 * 微信分享*
	 *
	 * @param request
	 * @param resp
	 * @param model
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/getwxapp", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult wchatShare(HttpServletRequest request, @RequestBody String json) {
		LOGGER.info("用户请求的数据:" + json);
		BlogUtil.inlog(json, "", "mit/user/getwxapp", "getwxapp", "req");
		WchatShareReq wchatShareReq = JSON.parseObject(json, WchatShareReq.class);
		AjaxResult ajaxResult = new AjaxResult();
		if (StringUtils.isEmpty(wchatShareReq.getType())) {
			LOGGER.info("type参数不能为空");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.USER_PARAM_ISNULL);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "type不能为空", tips);
			} else {
				ajaxResult = new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "type不能为空",
						"[" + ErrorCodeConstants.USER_PARAM_ISNULL + "]" + "type不能为空");
			}
			return ajaxResult;
		}
		if (StringUtils.isEmpty(wchatShareReq.getChannelid())) {
			LOGGER.info("channelid参数不能为空");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.USER_PARAM_ISNULL);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "channelid不能为空", tips);
			} else {
				ajaxResult = new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "channelid不能为空",
						"[" + ErrorCodeConstants.USER_PARAM_ISNULL + "]" + "channelid不能为空");
			}
			return ajaxResult;
		}
		/*String callbackurl = baseService.getBaseByBkey(WXCALLBACKURL);
		if (StringUtils.isEmpty(callbackurl)) {
			LOGGER.info("微信回调地址不存在");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SYS_CHANNEL_WXCALLBACKURL);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXCALLBACKURL, "微信回调地址不存在", tips);
			} else {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXCALLBACKURL, "微信回调地址不存在",
						"[" + ErrorCodeConstants.SYS_CHANNEL_WXCALLBACKURL + "]" + "微信回调地址不存在");
			}
			return ajaxResult;
		}*/

		JSONObject obj = JSONObject.parseObject(json);
		String url = obj.getString("localurl");
		url=url.split("#")[0];
		LOGGER.info("解码url前:" + url);
		if(StringUtils.isNotBlank(url)) {
			try {
				url = URLDecoder.decode(url, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			} // 解码
		}
		LOGGER.info("解码url后:" + url);
		if ("1".equals(wchatShareReq.getType())||"3".equals(wchatShareReq.getType())||"4".equals(wchatShareReq.getType())) {
			try {
				ajaxResult = serWxService.wchatShare(wchatShareReq, url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("2".equals(wchatShareReq.getType())){
			if("1".equals(scope)) {
				scope = "snsapi_userinfo";
			}else if("2".equals(scope)){
				scope = "snsapi_base";
			}
			TMitChannel channel = iTMitChannelService.selectById(wchatShareReq.getChannelid());
			String appid = channel.getAppid();
			Map<String,String> map = new HashMap<>(2);
			map.put("scope", scope);
			map.put("appid", appid);
			ajaxResult.setContext(map);
			ajaxResult.setStatus(ErrorCodeConstants.SUCCESS);
			ajaxResult.setMessage("获取成功");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SUCCESS);
			if(StringUtils.isNotBlank(tips)){
				ajaxResult.setTips(tips);
			}else{
				ajaxResult.setTips("获取成功");
			}
		}
		String resJSON = JSON.toJSONString(ajaxResult);
		BlogUtil.inlog(resJSON, "", "mit/user/getwxapp", "getwxapp", "resp");
		return ajaxResult;
	}
	/*@RequestMapping(value = "/getCode", method = RequestMethod.GET)
	public void getCode(HttpServletRequest request) {
		System.out.println(request.getParameter("code"));
	}*/

	@RequestMapping(value = "/wxlogin", method = RequestMethod.POST)
	@ResponseBody
	public Map wxlogin(@RequestBody String json) {
		LOGGER.info("=============微信登录接口开始=============");
		// 接受前端请求记录内部日志
		AjaxResult ajaxResult = new AjaxResult();
		try {
			ajaxResult = serWxService.wxlogin(json);
		} catch (Exception e) {
			LOGGER.error("wxlogin接口错误：" + e.getMessage());
			ajaxResult.setTips("系统内部错误");
			ajaxResult.setMessage("系统内部错误");
			ajaxResult.setStatus(ErrorCodeConstants.INTERNAL_ERROR);
		}
		String tips = itMitErrorCodeService.getTips(ajaxResult.getStatus());
		if (StringUtils.isNotBlank(tips)) {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + tips);
		} else {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + ajaxResult.getTips());
		}
		LOGGER.info("=============微信登录接口结束=============");
		Map<String,Object> map = new HashMap<>();
		map.put("status", ajaxResult.getStatus());
		map.put("message", ajaxResult.getMessage());
		map.put("tips", ajaxResult.getTips());
		if("0".equals(ajaxResult.getStatus())) {
			Map<String,Object> context = (HashMap<String,Object>)ajaxResult.getContext();
			String token = (String)context.get("token");
			context.remove("token");
			map.put("token", token);
			map.put("context", context);
		}
		return map;
	}

	@RequestMapping(value = "/wxloginmix", method = RequestMethod.POST)
	@ResponseBody
	public Map wxloginmix(@RequestBody String json) {
		LOGGER.info("=============微信登录+手机登陆接口开始=============");
		// 接受前端请求记录内部日志
		AjaxResult ajaxResult = new AjaxResult();
		try {
			ajaxResult = serWxService.wxloginmix(json);
		} catch (Exception e) {
			LOGGER.error("wxloginmix接口错误：" + e.getMessage());
			ajaxResult.setTips("系统内部错误");
			ajaxResult.setMessage("系统内部错误");
			ajaxResult.setStatus(ErrorCodeConstants.INTERNAL_ERROR);
		}
		String tips = itMitErrorCodeService.getTips(ajaxResult.getStatus());
		if (StringUtils.isNotBlank(tips)) {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + tips);
		} else {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + ajaxResult.getTips());
		}
		LOGGER.info("=============微信登录+手机登陆接口结束=============");
		Map<String,Object> map = new HashMap<>();
		map.put("status", ajaxResult.getStatus());
		map.put("message", ajaxResult.getMessage());
		map.put("tips", ajaxResult.getTips());
		if("0".equals(ajaxResult.getStatus())) {
			Map<String,Object> context = (HashMap<String,Object>)ajaxResult.getContext();
			String token = (String)context.get("token");
			context.remove("token");
			map.put("token", token);
			map.put("context", context);
		}
		return map;
	}

	@RequestMapping(value = "/pushx", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult wchatPushx(HttpServletRequest request, @RequestBody String json) {
		LOGGER.info("用户请求的数据:" + json);
		AjaxResult ajaxResult = new AjaxResult();
		BlogUtil.inlog(json, "", "fire/user/pushx", "pushx", "req");
		WchatPushxReq wchatPushxReq = JSON.parseObject(json, WchatPushxReq.class);
		/*for (ContextReq context : wchatPushxReq.getContext()) {
			wchatPushxReq.setFirst(context.getFirst());
			wchatPushxReq.setKeyword1(context.getKeyword1());
			wchatPushxReq.setKeyword2(context.getKeyword2());
			wchatPushxReq.setKeyword3(context.getKeyword3());
			wchatPushxReq.setKeyword4(context.getKeyword4());
			wchatPushxReq.setKeyword5(context.getKeyword5());
			wchatPushxReq.setRemark(context.getRemark());
		}*/

		String result = serWxService.senMsg(wchatPushxReq);
		if ("success".equals(result)) {
			ajaxResult.setStatus(ErrorCodeConstants.SUCCESS);
			ajaxResult.setTips("微信推送成功！");
			ajaxResult.setMessage("微信推送成功");
		} else {
			ajaxResult.setStatus(ErrorCodeConstants.SYS_CHANNEL_WXSENDERROR);
			if("unnecessary".equals(result)) {
				ajaxResult.setTips("[" + ErrorCodeConstants.SYS_CHANNEL_WXSENDERROR + "]微信推送失败，该用户无需推送！");
				ajaxResult.setMessage("[" + ErrorCodeConstants.SYS_CHANNEL_WXSENDERROR + "]微信推送失败，该用户无需推送！");
			}else {
				ajaxResult.setTips("[" + ErrorCodeConstants.SYS_CHANNEL_WXSENDERROR + "]微信推送失败！");
				ajaxResult.setMessage("[" + ErrorCodeConstants.SYS_CHANNEL_WXSENDERROR + "]微信推送失败");
			}
		}
		return ajaxResult;
	}

	// 将jsonString转化为hashmap
	private HashMap<String, Object> fromJson2Map(String jsonString) {
		HashMap jsonMap = JSON.parseObject(jsonString, HashMap.class);

		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		for (Iterator iter = jsonMap.keySet().iterator(); iter.hasNext();) {
			String key = (String) iter.next();
			if (jsonMap.get(key) instanceof JSONArray) {
				JSONArray jsonArray = (JSONArray) jsonMap.get(key);
				List list = handleJSONArray(jsonArray);
				resultMap.put(key, list);
			} else {
				resultMap.put(key, jsonMap.get(key));
			}
		}
		return resultMap;
	}

	private List<HashMap<String, Object>> handleJSONArray(JSONArray jsonArray) {
		List list = new ArrayList();
		for (Object object : jsonArray) {
			JSONObject jsonObject = (JSONObject) object;
			HashMap map = new HashMap<String, Object>();
			for (Map.Entry entry : jsonObject.entrySet()) {
				if (entry.getValue() instanceof JSONArray) {
					map.put((String) entry.getKey(), handleJSONArray((JSONArray) entry.getValue()));
				} else {
					map.put((String) entry.getKey(), entry.getValue());
				}
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * 微信公众号webservice主服务接口，提供与微信服务器的信息交互
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/protal")
	public void wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {
		LOGGER.info("接入微信服务器开始。。。。。。。。。");
		// 微信服务器get传递的参数
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		// 微信工具类
		WxMpService wxService = new WxMpServiceImpl();

		// 注入token的配置参数
		/**
		 * 生产环境 建议将WxMpInMemoryConfigStorage持久化
		 */
		WxMpInMemoryConfigStorage wxConfigProvider = new WxMpInMemoryConfigStorage();
		// 注入token值
		wxConfigProvider.setToken("weixin");

		wxService.setWxMpConfigStorage(wxConfigProvider);

		boolean flag = wxService.checkSignature(timestamp, nonce, signature);

		PrintWriter out = response.getWriter();
		if (flag) {
			LOGGER.info("echostr:" + echostr);
			LOGGER.info("接入微信服务器结束。。。。。。。。。");
			out.print(echostr);
		}

		out.close();
		out = null;
	}

}
